using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Inspections.Queries;

/// <summary>
/// 分页查询设备点检记录。
/// </summary>
/// <param name="MachineryCode">设备编号</param>
/// <param name="MachineryName">设备名称，模糊查询</param>
/// <param name="LineId">产线 Id</param>
/// <param name="Result">点检结果</param>
/// <param name="StartTime">点检查询开始时间</param>
/// <param name="EndTime">点检查询结束时间</param>
/// <param name="PageNumber">页索引</param>
/// <param name="PageSize">每页数量</param>
public sealed record GetInspectionRecordListWithPagedQuery(
    string? MachineryCode,
    string? MachineryName,
    long? LineId,
    QualifiedEnum? Result,
    DateTime? StartTime,
    DateTime? EndTime,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<EquipInspectionRecordDto>>>;

internal sealed class GetInspectionRecordListWithPagedQueryHandler(IRepository<EquipInspectionRecord> repo)
    : IRequestHandler<GetInspectionRecordListWithPagedQuery, IResult<PagedList<EquipInspectionRecordDto>>>
{
    public async Task<IResult<PagedList<EquipInspectionRecordDto>>> Handle(GetInspectionRecordListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(request.MachineryCode), m => m.MachineryCode == request.MachineryCode)
            .WhereIF(!string.IsNullOrEmpty(request.MachineryName), m => m.MachineryName.Contains(request.MachineryName!))
            .WhereIF(request.LineId > 0, m => m.LineId == request.LineId)
            .WhereIF(request.Result != null, m => m.Result == request.Result)
            .WhereIF(request.StartTime != null, m => m.InspectionTime >=  request.StartTime.MinTime())
            .WhereIF(request.EndTime != null, m => m.InspectionTime <= request.EndTime.MaxTime())
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<EquipInspectionRecordDto>>());
    }
}
